package com.fj.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author fj
 * @date 2023/12/12 10:06
 */
public class GroupChatClient {
    private SocketChannel socketChannel;
    private Selector selector;
    private String ip;
    private int port;
    public GroupChatClient(String ip, int port){
        try {
            this.socketChannel = SocketChannel.open(new InetSocketAddress(ip, port));
            socketChannel.configureBlocking(false);
            this.selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_READ);
            this.ip = ip;
            this.port = port;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void login(){
        new Thread(()->{
            try {
                read();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String msg = scanner.nextLine();
            send(msg);
        }
    }

    private void send(String msg){
        try {
            System.out.println("我: "+ msg);
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void read() throws IOException{
        while (true){
            selector.select(1000);
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isReadable()){
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    try {
                        int read = socketChannel.read(byteBuffer);
                        if (read > 0){
                            String msg = new String(byteBuffer.array());
                            System.out.println(msg);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                iterator.remove();
            }
        }
    }

    public static void main(String[] args) {
        GroupChatClient client = new GroupChatClient("127.0.0.1", 6789);
        client.login();
    }
}
